package com.my.okhttps.test.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ejlchina.okhttps.HttpResult;
import com.ejlchina.okhttps.OkHttps;
import com.my.core.api.R;
import com.my.core.domain.exception.ServiceException;
import com.my.okhttps.test.service.IYiBaoService;
import com.my.okhttps.test.vo.YiBaoEmployeeBasePayDetailVo;
import com.my.okhttps.utils.security.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * 医保
 */
@Service
@Slf4j
public class YiBaoServiceImpl implements IYiBaoService {
    /**测试秘钥固定，不需自己生成*/
    public static String publicKeyStr;
    public static String privateKeyStr;
    /** 渠道编号*/
    public static String platId;
    /** 服务事项编号*/
    public static String serviceCode ;
    public static String base_url;
    /**医保标签*/
    public static final String YIBAO_TAR = "YIBAO";

    @Value("${yibao.publicKeyStr:}")
    public void setPublicKeyStr(String publicKeyStr) {
        YiBaoServiceImpl.publicKeyStr = publicKeyStr;
    }
    @Value("${yibao.privateKeyStr:}")
    public void setPrivateKeyStr(String privateKeyStr) {
        YiBaoServiceImpl.privateKeyStr = privateKeyStr;
    }
    @Value("${yibao.platId:}")
    public void setPlatId(String platId) {
        YiBaoServiceImpl.platId = platId;
    }
    @Value("${yibao.serviceCode:}")
    public void setServiceCode(String serviceCode) {
        YiBaoServiceImpl.serviceCode = serviceCode;
    }
    @Value("${yibao.baseUrl:}")
    public void setBase_url(String base_url) {
        YiBaoServiceImpl.base_url = base_url;
    }

    @FunctionalInterface
    interface DecryptObjFun {
        R decrypt(JSONObject data);
    }
    @FunctionalInterface
    interface DecryptArryFun {
        R decrypt(JSONArray data);
    }
//    @FunctionalInterface
//    interface DecryptFun<T extends List<?>> {
//        T decrypt(JSONObject data);
//    }
//    @FunctionalInterface
//    interface DecryptFun<T> {
//        T decrypt(JSONObject data);
//    }
    public R operationObj(HashMap<String,String> map,DecryptObjFun decryptFun){
        return operation(map,decryptFun,null);
    }
    public R operationArr(HashMap<String,String> map,DecryptArryFun decryptFun){
        return operation(map,null,decryptFun);
    }
    public R operation(HashMap<String,String> map,DecryptObjFun decryptObjFun,DecryptArryFun decryptArrFun){
        map.put("serviceCode", YiBaoServiceImpl.serviceCode);
        map.put("platId", YiBaoServiceImpl.platId);
        map.put("publicKeyStr", YiBaoServiceImpl.publicKeyStr);

        HttpResult httpResult = OkHttps.sync(base_url)
                .addUrlPara(map)
                .skipSerialPreproc()
                .tag(YIBAO_TAR)
                .post();
        HttpResult.Body body = httpResult.getBody();
        JSONObject jsonObject = JSON.parseObject(String.valueOf(body));
        Boolean success = jsonObject.getBoolean("success");
        if(success) {
            JSONObject resultData = jsonObject.getJSONObject("resultData");
            JSONObject data = resultData.getJSONObject("data");
            String errorCode = data.getString("errorCode");
            if("0".equals(errorCode)){
                String decrypt = SecurityUtil.decrypt(data.getInnerMap(), privateKeyStr);
                if(decryptArrFun!=null){
                    JSONArray jsonArray = JSON.parseArray(decrypt);
                    return decryptArrFun.decrypt(jsonArray);
                }else{
                    JSONObject dataJsonObject = JSON.parseObject(decrypt);
                    return decryptObjFun.decrypt(dataJsonObject);
                }
            }else{
                String errorMsg = data.getString("errorMsg");
                return R.fail(errorMsg);
            }
        }
        throw new ServiceException(jsonObject.toJSONString());
    }


    /**
     * 获取医保账户余额
     * @param name 姓名
     * @param idCard 身份证
     * @return
     */
    @Override
    public R getAccountBalance(String name, String idCard){
        HashMap<String,String> map = new HashMap<>();
        //接口编号
        map.put("apiNum","GGFWK002");
        map.put("cardId",idCard);
        map.put("name",name);
//        {"lists":{},"resultData":{"data":{"errorCode":"0","errorMsg":"","valueData":
//        {"aae240":"149.1"}}},"success":true}
        R result = operationObj(map, valueData -> {
            String aae240 = valueData.getString("aae240");
            return R.data(aae240);
        });
        return result;
    }

    /**
     * 职工基本医疗缴费明细
     * @param name
     * @param idCard
     * @param starDate 202001
     * @param endDate 202012
     * @return
     */
    @Override
    public R getEmployeeBasePayDetail(String name, String idCard,String starDate,String endDate){
        HashMap<String,String> map = new HashMap<>();
        //接口编号
        map.put("apiNum","GGFWK005");
        map.put("cardId",idCard);
        map.put("name",name);
        map.put("issue_1",starDate);
        map.put("issue_2",endDate);
//        {"lists":{},"resultData":{"data":{"errorCode":"0","errorMsg":"","valueData":[
//        {"AAE002":202008,"AKC031":0,"AAB004":"泸县兆雅镇卫生院（泸县兆雅中心卫生院）","AKC030":0},{"AAE002":202007,"AKC031":0,"AAB004":"泸县兆雅镇卫生院（泸县兆雅中心卫生院）","AKC030":0},{"AAE002":202006,"AKC031":0,"AAB004":"泸县兆雅镇卫生院（泸县兆雅中心卫生院）","AKC030":0},{"AAE002":202005,"AKC031":0,"AAB004":"泸县兆雅镇卫生院（泸县兆雅中心卫生院）","AKC030":0},{"AAE002":202004,"AKC031":0,"AAB004":"泸县兆雅镇卫生院（泸县兆雅中心卫生院）","AKC030":0},{"AAE002":202003,"AKC031":0,"AAB004":"泸县兆雅镇卫生院（泸县兆雅中心卫生院）","AKC030":0},{"AAE002":202002,"AKC031":0,"AAB004":"泸县兆雅镇卫生院（泸县兆雅中心卫生院）","AKC030":0},{"AAE002":202001,"AKC031":0,"AAB004":"泸县兆雅镇卫生院（泸县兆雅中心卫生院）","AKC030":0}]}},"success":true}
        R result = operationArr(map, valueDatas -> {
            Iterator<Object> iterator = valueDatas.iterator();
            List<YiBaoEmployeeBasePayDetailVo> returnVos = new ArrayList<YiBaoEmployeeBasePayDetailVo>();
            while (iterator.hasNext()) {
                JSONObject next = (JSONObject) iterator.next();
                String akc030 = next.getString("AKC030");
                String akc031 = next.getString("AKC031");
                String aae002 = next.getString("AAE002");
                String aab004 = next.getString("AAB004");
                YiBaoEmployeeBasePayDetailVo yiBaoEmployeeBasePayDetailVo =
                        new YiBaoEmployeeBasePayDetailVo(akc030,akc031,aae002,aab004);
                returnVos.add(yiBaoEmployeeBasePayDetailVo);
            }
            return R.data(returnVos);
        });
        return result;
    }

}
